package servlet;

import dao.EquipmentDao;
import dao.EquipmentDaoImpl;
import dao.TableUsingDaoImpl;
import dao.UsingDaoImpl;
import utils.string.session.SessionStringUtil;
import vo.Using;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;

public class AddUsingServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在增加到维修中的数目，在设备表中的数据也得修改
        UsingDaoImpl UsingDao = new UsingDaoImpl();
        Using Using = new Using();
        //获取数据
        String using_reason = req.getParameter("using_reason");
        int using_num = Integer.parseInt(req.getParameter("using_num"));
        int equipmentId = Integer.parseInt(req.getParameter("equipmentId"));
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        //获取现在的时间
        java.util.Date utilDate = new java.util.Date();
        Date date = new Date(utilDate.getTime());
        Using.setUsing_date(date);
        Using.setUsing_num(using_num);
        Using.setUsing_reason(using_reason);
        Using.setEquip_id(equipmentId);
        Using.setUser_id(user.getUser_id());
        UsingDao.insertUsing(Using);
        //更改设备里面的数目
        EquipmentDaoImpl equipmentDao = new EquipmentDaoImpl();
        equipmentDao.changeEquipment(equipmentId,using_num, EquipmentDao.SUBSTRACT_EQUIPMENT_NUM);//因为是借用出去所以原来的数目会下降
        //页面跳转
        jumpToJSP(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        jumpToJSP(req,resp);
    }

    private void jumpToJSP(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //在这里进行判断用户的权限进行不同的JSP页面跳转
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        TableUsingDaoImpl tableUsingDao = new TableUsingDaoImpl();
        //对应的用户的界面
        HashMap userUsings = tableUsingDao.selectByUserId(user.getUser_id());
        HashMap allUsings = tableUsingDao.selectAll();
        req.getSession().setAttribute(SessionStringUtil.ALL_USING,allUsings);
        req.getSession().setAttribute(SessionStringUtil.USER_USINGS,userUsings);
        //listener 中只监听一次，所以还得传送数据
        if(user.getAuth_id() == 1){
            resp.sendRedirect("/equipmentManager_war_explode/manageAllUsing.jsp");//跳转到管理者的Fix界面
        }else{
            resp.sendRedirect("/equipmentManager_war_explode/manageUserUsing.jsp");//普通用户的界面
        }
    }
}
